package com.terrygjt.myshop;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.terrygjt.myshop.R;

public class MainActivity extends AppCompatActivity {
    public final int CUSTOMIZED_REQUEST_CODE = 0x0000ffff;
    private TextView Tv_query_result;
    private EditText CommodityBarcode,CommodityName;
    private EditText CommodityPrice1,CommodityPrice2,CommodityPrice3;
    private EditText CommoditySpecification1,CommoditySpecification2,CommoditySpecification3;
    private String commodityBarcode,commodityName;
    private String commodityPrice1,commodityPrice2,commodityPrice3;
    private String commoditySpecification1,commoditySpecification2,commoditySpecification3;
    private SqliteThread sqliteThread;
    private Handler handler_for_sqliteThread;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        verifyStoragePermissions(this);
        Tv_query_result=findViewById(R.id.tv_query_result);
        CommodityBarcode=findViewById(R.id.CommodityBarcode);
        CommodityName=findViewById(R.id.CommodityName);
        CommodityPrice1=findViewById(R.id.CommodityPrice1);
        CommodityPrice2=findViewById(R.id.CommodityPrice2);
        CommodityPrice3=findViewById(R.id.CommodityPrice3);
        CommoditySpecification1=findViewById(R.id.CommoditySpecification1);
        CommoditySpecification2=findViewById(R.id.CommoditySpecification2);
        CommoditySpecification3=findViewById(R.id.CommoditySpecification3);
        initHandler();
        sqliteThread=new SqliteThread(this,handler_for_sqliteThread);
        sqliteThread.start();
        sqliteThread.initHandler(sqliteThread.getLooper());
    }
    public static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    /*** 验证读取sd卡的权限** @param activity*/
    public boolean verifyStoragePermissions(Activity activity) {
        /*******below android 6.0*******/
        if (Build.VERSION.SDK_INT < 23) {return true;}
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            return false;
        } else {
            return true;
        }
    }
    /** * 请求权限回调 * * @param requestCode * @param permissions * @param grantResults */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_EXTERNAL_STORAGE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {showToast("授权成功");
    } else {showToast("授权失败,请去设置打开权限");
    }}}
    public void scanBarcode(View view) {
        new IntentIntegrator(this).initiateScan();
    }
    private void showToast(String s){
        Toast.makeText(this, s, Toast.LENGTH_LONG).show();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != CUSTOMIZED_REQUEST_CODE && requestCode != IntentIntegrator.REQUEST_CODE) {
            // This is important, otherwise the result will not be passed to the fragment
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }
        switch (requestCode) {
            case CUSTOMIZED_REQUEST_CODE: {
                Toast.makeText(this, "REQUEST_CODE = " + requestCode, Toast.LENGTH_LONG).show();
                break;
            }
            default:
                break;
        }

        IntentResult result = IntentIntegrator.parseActivityResult(resultCode, data);

        if(result.getContents() == null) {
//            Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
            Log.i("线程onActivityResult","Cancelled");
        } else {
            Log.i("线程onActivityResult","Scanned: " + result.getContents());
//            Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
            CommodityBarcode.setText(result.getContents());
            queryCommodityData(CommodityBarcode);
        }
    }
    private void initHandler(){
        handler_for_sqliteThread = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what==4) {//处理queryData的返回结果
                    String[] ss4=(String[])msg.obj;
                    Log.i("线程msg.what==4","queryData：");

                }
                else if (msg.what == 5 ) {//处理queryAllData的返回结果
                    String[] ss5=(String[])msg.obj;
                    Log.i("线程msg.what==5","queryData：");
                    if ("".equals(ss5[0])||ss5[0]==null){
                        Toast.makeText(MainActivity.this, "此商品不存在，请新建！", Toast.LENGTH_LONG).show();
                    }else {
                        Toast.makeText(MainActivity.this, "查询成功！", Toast.LENGTH_LONG).show();
                        CommodityName.setText(ss5[1]);
                        CommoditySpecification1.setText(ss5[3]);//为了输入方便，查询成功才修改规格
                        CommoditySpecification2.setText(ss5[5]);
                        CommoditySpecification3.setText(ss5[7]);
                    }
//                    CommodityName.setText(ss5[1]);
                    CommodityPrice1.setText(ss5[2]);
                    CommodityPrice2.setText(ss5[4]);
                    CommodityPrice3.setText(ss5[6]);
                }
                else if (msg.what == 6 ) {//处理queryAllData的返回结果
                    String ss5=(String)msg.obj;
                    Log.i("线程msg.what==6","queryData：");
                    Tv_query_result.append(ss5+"\n");
                }
            }
        };
    }
    public void queryCommodityData(View view){//查询商品，若已有则显示在界面上
        commodityBarcode=CommodityBarcode.getText().toString();
        if("".equals(commodityBarcode)){
            Toast.makeText(this, "商品条码为空！请先输入或扫描条形码", Toast.LENGTH_LONG).show();
            Log.i("线程queryCommodityData","商品条码为空！请先输入或扫描条形码");
        }else{
            sqliteThread.queryCommodityData(commodityBarcode);//由于数据库无法直接访问，所以无法直接获取到返回值，返回值在handler_for_sqliteThread中处理
        }
    }
    public void insertCommodity(View view){//新建商品
        commodityBarcode=CommodityBarcode.getText().toString();
        commodityName=CommodityName.getText().toString();
        commodityPrice1=CommodityPrice1.getText().toString();
        commodityPrice2=CommodityPrice2.getText().toString();
        commodityPrice3=CommodityPrice3.getText().toString();
        commoditySpecification1=CommoditySpecification1.getText().toString();
        commoditySpecification2=CommoditySpecification2.getText().toString();
        commoditySpecification3=CommoditySpecification3.getText().toString();
        if("".equals(commodityBarcode)){
            Toast.makeText(this, "商品条码为空！请先输入或扫描条形码", Toast.LENGTH_LONG).show();
            Log.i("线程insertCommodity","商品条码为空！请先输入或扫描条形码");
        }else{
            sqliteThread.insertData(commodityBarcode,commodityName,commodityPrice1,commoditySpecification1,
                    commodityPrice2,commoditySpecification2,commodityPrice3,commoditySpecification3);
            Log.i("线程insertCommodity","插入"+commodityBarcode+"-"+commodityName+"-"+commodityPrice1+"/"+commoditySpecification1+"-"+
                    commodityPrice2+"/"+commoditySpecification2+"-"+commodityPrice3+"/"+commoditySpecification3);
            Toast.makeText(this, "新建成功", Toast.LENGTH_LONG).show();
        }
    }
    public void updateCommodity(View view){//修改商品
        commodityBarcode=CommodityBarcode.getText().toString();
        commodityName=CommodityName.getText().toString();
        commodityPrice1=CommodityPrice1.getText().toString();
        commodityPrice2=CommodityPrice2.getText().toString();
        commodityPrice3=CommodityPrice3.getText().toString();
        commoditySpecification1=CommoditySpecification1.getText().toString();
        commoditySpecification2=CommoditySpecification2.getText().toString();
        commoditySpecification3=CommoditySpecification3.getText().toString();
        if("".equals(commodityBarcode)){
            Toast.makeText(this, "商品条码为空！请先输入或扫描条形码", Toast.LENGTH_LONG).show();
            Log.i("线程updateCommodity","商品条码为空！请先输入或扫描条形码");
        }else{
            sqliteThread.updateData(commodityBarcode,commodityName,commodityPrice1,commoditySpecification1,
                    commodityPrice2,commoditySpecification2,commodityPrice3,commoditySpecification3);
            Log.i("线程updateCommodity","修改"+commodityBarcode+"-"+commodityName+"-"+commodityPrice1+"/"+commoditySpecification1+"-"+
                    commodityPrice2+"/"+commoditySpecification2+"-"+commodityPrice3+"/"+commoditySpecification3);
            Toast.makeText(this, "修改成功", Toast.LENGTH_LONG).show();
        }
    }
    public void deleteCommodity(View view){//删除商品
        commodityBarcode=CommodityBarcode.getText().toString();
        if("".equals(commodityBarcode)){
            Toast.makeText(this, "商品条码为空！请先输入或扫描条形码", Toast.LENGTH_LONG).show();
            Log.i("线程deleteCommodity","商品条码为空！请先输入或扫描条形码");
        }else{
            sqliteThread.deleteData(commodityBarcode);
            Log.i("线程deleteCommodity","删除"+commodityBarcode);
            Toast.makeText(this, "删除"+commodityBarcode, Toast.LENGTH_LONG).show();
        }
    }
    public void queryAllCommodityAndLog(View view){//查询数据库所有商品并log，测试用
        Tv_query_result.setText("");
        sqliteThread.queryAllCommodityAndLog();
    }
    @Override
    protected void onDestroy() {
        sqliteThread.closeSQLiteDatabase();
        super.onDestroy();
    }
}
